﻿// MIT License
//
// Copyright (c) 2021-present zuohuaijun, Daming Co.,Ltd and Contributors
//
// 电话/微信：18020030720 QQ群1：87333204 QQ群2：252381476

using Admin.NET.Application.Const;
using Admin.Net.InformationPlatform.Entity;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using Nest;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Admin.NET.Core;
using Admin.Net.InformationPlatform.Entity.Equipment;
using Admin.Net.InformationPlatform.Service.Equipment.Dto;
using Admin.Net.InformationPlatform.Service.Equipment_Para.Dto;
using Admin.Net.InformationPlatform.Entity.ProdectFile;
using Furion.FriendlyException;
using Admin.Net.InformationPlatform.Entity.Maintenance;
using Admin.Net.InformationPlatform.Service.ProjectFile.Dto;

namespace Admin.Net.InformationPlatform.Service.Equipment_Para 
{
    /// <summary>
    /// 华为验厂-设备参数管理
    /// </summary>
    [ApiDescriptionSettings(groups: "HWYC", Name = "设备参数管理", Tag = "设备参数管理", Order = 200)]

    public class EquipmentParaService : IDynamicApiController, ITransient
    {
        /// <summary>
        /// 单例数据链接
        /// </summary>
        ISqlSugarClient db;
        /// <summary>
        /// T100数据库
        /// </summary>
        private SqlSugarProvider _T100Db;
        private SqlSugarProvider _SjDb;
        private SqlSugarProvider _plm;
        private SqlSugarProvider _Dilon;


        /// <summary>
        /// 用户信息
        /// </summary>
        TokenUser _User;
        /// <summary>
        /// 设备参数管理
        /// </summary>
        /// <param name="db"></param>
        public EquipmentParaService(ISqlSugarClient db)
        {
            this.db = db;
            this._T100Db = this.db.AsTenant().GetConnection(T100TestArea.ConfigId);
            this._SjDb = this.db.AsTenant().GetConnection(SJDB.ConfigId);
            this._plm = this.db.AsTenant().GetConnection(PLM.ConfigId);
            this._Dilon = this.db.AsTenant().GetConnection(Dilon.ConfigId);
            // 获取 `Jwt` 存储的信息 企业编号与据点信息
            _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db, _Dilon);

        }
        /// <summary>
        /// 设备列表（分页）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/HWYC/GetSpecificInformationPagedList")]
        public async Task<SqlSugarPagedList<HWSpecificInformationOutPut>> GetSpecificInformationPagedList(SelectEquipmentBasicInput input)
        {
            var output = await _SjDb.Queryable<HWEquipmentBasicZi>()
                .LeftJoin<HWEquipmentBasicInformation>((z,l) => (z.DEVICENUMBER==l.DEVICENUMBER ))
                .LeftJoin<HWSpecificInformation>((z,l, m) => ( z.DEVICENUMBER == m.DEVICENUMBER && z.MATERIALNO ==m.MATERIALNO))
          //  .Where((z, l, m) => l.LIFECYCLE == 0)
           // .WhereIF(!string.IsNullOrEmpty(input.MATERIALNO), (l) => (l.MATERIALNO.Contains(input.MATERIALNO)))//料号
            .WhereIF(!string.IsNullOrEmpty(input.DEVICENUMBER), (z) => (z.DEVICENUMBER.Contains(input.DEVICENUMBER)))//设备编号
            .OrderBy((z, l, m) => l.DEVICENUMBER) //创建日期排序
            .OrderBy((z, l, m) => l.CREATETIME, OrderByType.Desc) //创建日期排序
            .Select((z,l, m) => new HWSpecificInformationOutPut
            {
                EID = m.EID,
                MATERIALNO = z.MATERIALNO,
                ITEMNAME = z.ITEMNAME,
                EQUIPMENTSPECS = z.EQUIPMENTSPECS,
                EQUIPMENTTYPENO = l.EQUIPMENTTYPENO,
                DEVICENUMBER = l.DEVICENUMBER,
                STOVETEMPERATUREMAX = m.STOVETEMPERATUREMAX,
                STOVETEMPERATUREMIN = m.STOVETEMPERATUREMIN,
                BEAKTEMPERATUREMAX = m.BEAKTEMPERATUREMAX,
                BEAKTEMPERATUREMIN = m.BEAKTEMPERATUREMIN,
                GOOSENECKTEMPERATUREMAX = m.GOOSENECKTEMPERATUREMAX,
                GOOSENECKTEMPERATUREMIN = m.GOOSENECKTEMPERATUREMIN,
                EJECTTIMEMAX = m.EJECTTIMEMAX,
                EJECTTIMEMIN = m.EJECTTIMEMIN,
                COOLINGTIMEMAX = m.COOLINGTIMEMAX,
                COOLINGTIMEMIN = m.COOLINGTIMEMIN,
                SPRAYTIMEMAX = m.SPRAYTIMEMAX,
                SPRAYTIMEMIN = m.SPRAYTIMEMIN,
                LOCKMOULDFORCE_MAX = m.LOCKMOULDFORCE_MAX,
                LOCKMOULDFORCEMIN = m.LOCKMOULDFORCEMIN,
                TOTALPRESSUREMAX = m.TOTALPRESSUREMAX,
                TOTALPRESSUREMIN = m.TOTALPRESSUREMIN,
                MRONO = m.MRONO,
                MRONAME = m.MRONAME


            }).ToPagedListAsync(input.Page, input.PageSize);

            return output;

        }
        /// <summary>
        /// 增加设备参数记录
        /// </summary>
        /// <returns></returns>
        [HttpPost("/HWYC/AddHWSpecificInformation")]
        public async Task<string> AddHWSpecificInformation(HWSpecificInformation input)
        {
            //判断单据存在
            int cnt = await _SjDb.Queryable<HWSpecificInformation>()
                .Where(a => a.MATERIALNO == input.MATERIALNO)
                .Where(a => a.DEVICENUMBER == input.DEVICENUMBER)
                .Select(a => a.EID)
                .CountAsync();
            if (cnt != 0)//有数据时，修改数据
            {
                //提交
                try
                {
                    _SjDb.Ado.BeginTran();
                    int count = await _SjDb.Updateable<HWSpecificInformation>()
                     
               .SetColumns(a => a.STOVETEMPERATUREMAX == input.STOVETEMPERATUREMAX)
               .SetColumns(a => a.STOVETEMPERATUREMIN == input.STOVETEMPERATUREMIN)
               .SetColumns(a => a.BEAKTEMPERATUREMAX == input.BEAKTEMPERATUREMAX)
               .SetColumns(a => a.BEAKTEMPERATUREMIN == input.BEAKTEMPERATUREMIN)
               .SetColumns(a => a.GOOSENECKTEMPERATUREMAX == input.GOOSENECKTEMPERATUREMAX)
               .SetColumns(a => a.GOOSENECKTEMPERATUREMIN == input.GOOSENECKTEMPERATUREMIN)
               .SetColumns(a => a.EJECTTIMEMAX == input.EJECTTIMEMAX)
               .SetColumns(a => a.EJECTTIMEMIN == input.EJECTTIMEMIN)
               .SetColumns(a => a.COOLINGTIMEMAX == input.COOLINGTIMEMAX)
               .SetColumns(a => a.COOLINGTIMEMIN == input.COOLINGTIMEMIN)
               .SetColumns(a => a.SPRAYTIMEMAX == input.SPRAYTIMEMAX)
               .SetColumns(a => a.SPRAYTIMEMIN == input.SPRAYTIMEMIN)
               .SetColumns(a => a.LOCKMOULDFORCE_MAX == input.LOCKMOULDFORCE_MAX)
               .SetColumns(a => a.LOCKMOULDFORCEMIN == input.LOCKMOULDFORCEMIN)
               .SetColumns(a => a.TOTALPRESSUREMAX == input.TOTALPRESSUREMAX)
               .SetColumns(a => a.TOTALPRESSUREMIN == input.TOTALPRESSUREMIN)
               .SetColumns(a => a.MRONO == input.MRONO)
               .SetColumns(a => a.MRONAME == input.MRONAME)
               .Where(a => a.EID == input.EID)

                        .ExecuteCommandAsync();

                    if (count != 1)
                    {
                        throw Oops.Oh("修改失败！");
                    }
                    _SjDb.Ado.CommitTran();
                    return "修改成功！";
                }
                catch (Exception e)
                {
                    _SjDb.Ado.RollbackTran();
                    throw Oops.Oh($"异常：{e.Message}");
                }
            }
            else
            {
            var details = new HWSpecificInformation
            {
                MATERIALNO = input.MATERIALNO,
                DEVICENUMBER = input.DEVICENUMBER,
                STOVETEMPERATUREMAX = input.STOVETEMPERATUREMAX,
                STOVETEMPERATUREMIN = input.STOVETEMPERATUREMIN,
                BEAKTEMPERATUREMAX = input.BEAKTEMPERATUREMAX,
                BEAKTEMPERATUREMIN = input.BEAKTEMPERATUREMIN,
                GOOSENECKTEMPERATUREMAX = input.GOOSENECKTEMPERATUREMAX,
                GOOSENECKTEMPERATUREMIN = input.GOOSENECKTEMPERATUREMIN,
                EJECTTIMEMAX = input.EJECTTIMEMAX,
                EJECTTIMEMIN = input.EJECTTIMEMIN,
                COOLINGTIMEMAX = input.COOLINGTIMEMAX,
                COOLINGTIMEMIN = input.COOLINGTIMEMIN,
                SPRAYTIMEMAX = input.SPRAYTIMEMAX,
                SPRAYTIMEMIN = input.SPRAYTIMEMIN,
                LOCKMOULDFORCE_MAX = input.LOCKMOULDFORCE_MAX,
                LOCKMOULDFORCEMIN = input.LOCKMOULDFORCEMIN,
                TOTALPRESSUREMAX = input.TOTALPRESSUREMAX,
                TOTALPRESSUREMIN = input.TOTALPRESSUREMIN,
                MRONO = input.MRONO,
                MRONAME = input.MRONAME
            };
            #region 插入事务
            try
            {
                //开启事务
                _SjDb.Ado.BeginTran();
                int cnt1 = await _SjDb.Insertable<HWSpecificInformation>(details).ExecuteCommandAsync();

                if (cnt1 == 0)
                {
                    throw Oops.Oh($"新建任务失败！");
                }
                //提交事务
                _SjDb.Ado.CommitTran();
                return "插入成功";
            }
            catch (Exception e)
            {
                //回滚事务
                _SjDb.Ado.RollbackTran();
                throw Oops.Oh($"异常：{e.Message}");
                }
            }
            #endregion

        }
        /// <summary>
        /// 设备参数删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/HWYC/DeleteHWSpecificInformation")]
        public async Task<string> DeleteHWSpecificInformation(HWSpecificInformationInput input)
        {
            //判断单据存在
            int cnt = await _SjDb.Queryable<HWSpecificInformation>()
                .Where(a => a.EID == input.ID)
                .Select(a => a.EID)
                .CountAsync();
            if (cnt == 0)
            {
                throw Oops.Oh("任务不存在，驳回！");
            }
            else
            {
                //提交
                try
                {
                    _SjDb.Ado.BeginTran();
                    int count = await _SjDb.Deleteable<HWSpecificInformation>()
                        .Where(a => a.EID == input.ID)
                        .ExecuteCommandAsync();

                    if (count != 1)
                    {
                        throw Oops.Oh("删除失败！");
                    }
                    _SjDb.Ado.CommitTran();
                    return "删除成功！";
                }
                catch (Exception e)
                {
                    _SjDb.Ado.RollbackTran();
                    throw Oops.Oh($"异常：{e.Message}");
                }
            }
        }
    }
}